/*******************************************************************************
 * Copyright (c) 2010 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
package com.googlecode.ssdutils.beanconverter.factory;

import com.googlecode.ssdutils.beanconverter.api.BeanConverter;

/**
 * @author Sylvain Sicard
 * @param <S>
 * @param <T>
 * 
 */
public class LazyInitBeanConverterImpl<S, T> implements BeanConverter<S, T> {

	private BeanConverter<S, T> delegate;
	private final Class<S> from;
	private final Class<T> to;
	private final LazyBeanConverterFactory<S, T> lazyBeanConverterFactory;

	/**
	 * @param from
	 * @param to
	 * @param lazyBeanConverterFactory
	 */
	public LazyInitBeanConverterImpl(Class<S> from, Class<T> to,
			LazyBeanConverterFactory<S, T> lazyBeanConverterFactory) {
		this.from = from;
		this.to = to;
		this.lazyBeanConverterFactory = lazyBeanConverterFactory;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.googlecode.ssdutils.beanconverter.api.BeanConverter#convert(java.
	 * lang.Object)
	 */
	public T convert(S sourceBean) {
		if (delegate == null) {
			lazyInit(sourceBean);
		}
		return delegate.convert(sourceBean);
	}

	/**
	 * @param sourceBean
	 */
	private void lazyInit(S sourceBean) {
		delegate = lazyBeanConverterFactory.getLazyConverter(from, to,
				sourceBean);
	}

}
